# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: meta_exec.py 
@time: 2019/7/9 下午1:22
"""

'''
在局部变量域中执行代码，主要体现exec与locals之间关系
'''

# Error Example use
def test():
    a = 13
    exec('b = a + 1')
    print(a)
    print(b)
# print(test())

# Example use
def test1():
    a = 13
    loc = locals()
    exec('b = a + 1')
    b = loc['b']
    print(b)
    return ''

print(test1())

# 在exec中变量是否覆盖
def test2():
    x = 0
    exec('x += 1')
    print('x =',x)
    return ''

print(test2())

def test2_1():
    x = 0
    loc = locals()
    print('before: ', loc)
    exec('x += 1')
    print('after: ', loc)
    print('x = ', x)
    return ''
print(test2_1())

# 以上例子其实x的值没改变，下面实现x的改变
def test2_2():
    a = 13
    loc = {'a':a}
    glb = {}
    print('before: ', loc, glb)
    exec('b = a + 1', glb, loc)
    print('after: ', loc)
    b = loc['b']
    print('b = ', b)
    return ''

print(test2_2())
